import fetch from '@system.fetch'
import { URL } from '../setting'
import resolveData from './resolveData'

function requestHandle(params) {
  return new Promise((resolve, reject) => {
    fetch
      .fetch({
        url: params.url,
        method: params.method,
        data: params.data
      })
      .then(response => {
        const result = response.data
        const code = result.code
        let data = result.data
        if (result.data && !result.data.match(/cache/)) {
          data = JSON.parse(result.data)
        }
        code === 200 ? resolve(data) : reject(`code: ${code}`)
      })
      .catch((error, code) => {
        console.log(` request fail, code = ${code}`)
        reject(error)
      })
  })
}
function queryString(url, query) {
  let str = []
  for (let key in query) {
    if (typeof query[key] === 'object') {
      query[key] = encodeURIComponent(JSON.stringify(query[key]))
    } else if (query[key]) {
      query[key] = encodeURIComponent(query[key])
    }
    if (query[key] === undefined) {
      str.push(key + '=')
    } else {
      str.push(key + '=' + query[key])
    }
  }
  let paramStr = str.join('&')
  return paramStr ? `${url}?${paramStr}` : url
}
export const ajax = {
  post: function(params) {
    return requestHandle({
      method: 'post',
      url: URL,
      data: params
    })
  },
  get: function(params, info, ua) {
    return requestHandle({
      method: 'get',
      url: queryString(URL, resolveData(params, info, ua))
    })
  }
}
export const sendMonitor = params => {
  return fetch.fetch({
    url: params.url,
    header: {
      'User-Agent': params.ua
    }
  })
}
